package com.hiecho.service;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;

public class NettyService {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel sc = ServerSocketChannel.open();
        sc.configureBlocking(false);
        Selector selector=Selector.open();


        sc.register(selector, SelectionKey.OP_ACCEPT, null);
        sc.bind(new InetSocketAddress(9090));
        selector.select();

        Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
        while (iterator.hasNext()) {
            SelectionKey next = iterator.next();
            iterator.remove();
            if (next.isAcceptable()) {
                ServerSocketChannel channel =(ServerSocketChannel) next.channel();
                SocketChannel accept = channel.accept();
                accept.configureBlocking(false);
                SelectionKey register = accept.register(selector, 0, null);
                register.interestOps(SelectionKey.OP_READ);
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < 50000000;i++) {
                    sb.append('a');
                }
                ByteBuffer encode = Charset.defaultCharset().encode(sb.toString());
                int write = accept.write(encode);
                System.out.println(write);
                if (encode.hasRemaining()) {
                    register.interestOps(SelectionKey.OP_WRITE);
                }
            }
        }
    }
}
